#!/bin/sh

if [ "$1" = "autoconf" ]; then
	echo 'yes'
	exit 0
fi

if [ "$1" = "config" ]; then
	cat <<EOF
graph_title TCP Connections
graph_category network
graph_vlabel connections
graph_args --base 1000 -l 0
graph_info This graph shows the TCP connections states of all the network interfaces combined
CLOSED.label CLOSED
CLOSED.colour COLOUR3
IDLE.label IDLE
IDLE.colour COLOUR6
BOUND.label BOUND
BOUND.colour COLOUR12
LISTEN.label LISTEN
LISTEN.colour COLOUR0
SYN_SENT.label SYN_SENT
SYN_RCVD.label SYN_RCVD
ESTABLISHED.label ESTABLISHED
ESTABLISHED.colour COLOUR1
CLOSE_WAIT.label CLOSE_WAIT
FIN_WAIT_1.label FIN_WAIT_1
CLOSING.label CLOSING
LAST_ACK.label LAST_ACK
FIN_WAIT_2.label FIN_WAIT_2
TIME_WAIT.label TIME_WAIT
TIME_WAIT.colour COLOUR2
EOF
	exit 0
fi

netstat -an -P tcp -f inet -f inet6 | awk '
NF < 1 {
	header = NR
} 
header + 3 < NR {
	states[$7]++
}
BEGIN {
	states["CLOSED"]     = 0
	states["IDLE"]       = 0
	states["BOUND"]      = 0
	states["LISTEN"]     = 0
	states["SYN_SENT"]   = 0
	states["SYN_RCVD"]   = 0
	states["ESTABLISHED"]= 0
	states["CLOSE_WAIT"] = 0
	states["FIN_WAIT_1"] = 0
	states["CLOSING"]    = 0
	states["LAST_ACK"]   = 0
	states["FIN_WAIT_2"] = 0
	states["TIME_WAIT"]  = 0
}
END {
	for (idx in states) {
		 print idx ".value " states[idx]
	}
}'
